package com.example.cardemo

import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.example.cardemo.adapter.ModellistAdapter
import com.example.cardemo.bean.BrandlistBean
import com.example.cardemo.bean.ModellistBean
import com.example.cardemo.databinding.ActivityModellistBinding
import com.example.cardemo.utils.CarApi
import com.example.cardemo.utils.RetrofitUtils
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class ModellistActivity : AppCompatActivity() {
    lateinit var binding: ActivityModellistBinding
    val mDatas = mutableListOf<ModellistBean.ResultBean>()
    val adapter: ModellistAdapter by lazy {
        ModellistAdapter(this, mDatas)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d("ModellistActivity", "onCreate called")
        binding = DataBindingUtil.setContentView(this, R.layout.activity_modellist)
        Log.d("ModellistActivity", "Layout loaded")
        val bean: BrandlistBean.ResultBean? = intent.getParcelableExtra("bean")
        if (bean != null) {
            binding.title = bean.name
            binding.adapter = adapter
            bean.id?.let { loadDatas(it) }
        } else {
            Toast.makeText(this, "没有数据被接收到！", Toast.LENGTH_SHORT).show()
            finish()
        }
    }

    private fun loadDatas(series_id: String) {
        val api = RetrofitUtils.getApi(CarApi.base_url, CarApi::class.java)
        val call = api.getModellist(CarApi.key, series_id)
        call?.enqueue(object : Callback<ModellistBean> {
            override fun onResponse(call: Call<ModellistBean>, response: Response<ModellistBean>) {
                val bean: ModellistBean? = response.body()
                mDatas.clear()
                bean?.result?.let {
                    mDatas.addAll(it)
                    adapter.notifyDataSetChanged()
                }
            }

            override fun onFailure(call: Call<ModellistBean>, t: Throwable) {
                Toast.makeText(this@ModellistActivity, "获取失败，原因是： ${t.message}", Toast.LENGTH_SHORT).show()
            }
        })
    }
}